<?php

namespace app\admin\controller\teacher;

use app\common\controller\Backend;
use fast\Random;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\Log;

/**
 * 
 *
 * @icon fa fa-circle-o
 */
class Teacher extends Backend
{
    
    /**
     * Teacher模型对象
     * @var \app\admin\model\teacher\Teacher
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\teacher\Teacher;
        //分类
        $this->view->assign("ClassList", model('\app\admin\model\allclass\Allclass')->getClassList());
        //标签
        $this->view->assign("TagsList", model('\app\admin\model\allclass\Tags')->getTagsList());
        //资质列表
        $this->view->assign("GradeList", model('\app\admin\model\grade\Grade')->getGradeList());

    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $list = $this->model
                ->where($where)
                ->where(array('status' => array('NEQ', 9)))
                ->order($sort, $order)
                ->paginate($limit);

            foreach ($list as $k => $v) {
                //分类
                $list[$k]['classid'] = model('\app\admin\model\allclass\Allclass')->getClassidInfo($v['classid']);
                //标签
                $list[$k]['tags'] =model('\app\admin\model\allclass\Tags')->gettagsInfo($v['tags']);
                //资质
                $list[$k]['grade'] =model('\app\admin\model\grade\Grade')->getgradeInfo($v['grade']);

                //性别
                if($v['sex'] == 1){
                    $list[$k]['sex'] = "男";
                }else if($v['sex'] == 2){
                    $list[$k]['sex'] = "女";
                }else if($v['sex'] == 3){
                    $list[$k]['sex'] = "不显示";
                }

            }

            $result = array("total" => $list->total(), "rows" => $list->items());
            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $this->token();
            $params = $this->request->post("row/a");
            if ($params) {

                /*处理分类标签*/
                $params['classid'] = join(",", $params['classid']).",";
                $params['tags'] = join(",", $params['tags']).",";
                $params['grade'] = join(",", $params['grade']).",";
                $params['createtime'] = time();

                /*判断是否为咨询师*/
                if($params['is_live'] > 0){
                    if(empty($params['mobile'])){
                        $this->error("请填写手机号码");
                    }else if(!preg_match("/^1[3456789]\d{9}$/", $params['mobile'])){
                        $this->error("手机号码格式不正确");
                    }

                    /*同步生成会员账号*/
                    $user_id = $this->addUserInfo($params['mobile']);
                    if($user_id !== false){
                        $params['user_id'] = $user_id;
                    }else{
                        $this->error("操作失败，请重试");
                    }
                }

                $result = false;
                try {
                    $result = $this->model->allowField(true)->insertGetId($params);
                    if ($result !== false) {
                        $this->success();
                    } else {
                        $this->error($this->model->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                } catch (\think\Exception $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {   
        $rows = $this->model->get($ids)->toArray();
        if (!$rows) {
            $this->error(__('No Results were found'));
        }
        if ($this->request->isPost()) {
            //$this->token();
            $row = $this->model->get(['id' => $ids]);
            if (!$row) {
                $this->error(__('No Results were found'));
            }
            $params = $this->request->post("row/a", [], 'strip_tags');
            if ($params) { 

                /*处理分类标签*/
                $params['classid'] = join(",", $params['classid']).",";
                $params['tags'] = join(",", $params['tags']).",";
                $params['grade'] = join(",", $params['grade']).",";
                $params['updatetime'] = time();

                if($params['is_live'] != $row->is_live){

                    if($params['is_live'] == 0){
                        $params['user_id'] = 0;
                        $this->getWriteLog('管理员取消教师咨询师资格(TeacherId:'.$row->id.')');
                    }else{

                        if(empty($params['mobile'])){
                            $this->error("请填写手机号码");
                        }else if(!preg_match("/^1[3456789]\d{9}$/", $params['mobile'])){
                            $this->error("手机号码格式不正确");
                        }
                        /*同步生成会员账号*/
                        $user_id = $this->addUserInfo($params['mobile']);
                        if($user_id !== false){
                            $params['user_id'] = $user_id;
                            $this->getWriteLog('管理员更新教师咨询师资格(TeacherId:'.$row->id.')');
                        }else{
                            $this->error("操作失败，请重试");
                        }
                        
                    }

                }

                Db::startTrans();
                try {
                    $row->save($params);
                    Db::commit();
                    $this->success();
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
            }
            $this->error();
            return;
        }

        $rows['classid'] = array_filter(explode(',',$rows['classid']));
        $rows['tags'] = array_filter(explode(',',$rows['tags']));
        $rows['grade'] = array_filter(explode(',',$rows['grade']));

        $this->view->assign("row", $rows);
        return $this->view->fetch();

    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }

        $this->model->where('id', $ids)->update(['status' => '9']);
        $this->success();
    }

    /**
     * 生成会员信息
     */
    public function addUserInfo($mobile = ''){

        if(empty($mobile)){
            return false;
        }

        //判断是否存在
        //$info = db('user')->where('username', $mobile)->find();
        $info = db('user')->where('mobile', $mobile)->find();
        if(empty($info)){
            //新增账号
            $username = $mobile;
            $password = '123456';
            $email = "";
            $extend = [];

            $ip = request()->ip();
            $time = time();

            $data = [
                'username' => $username,
                'password' => $password,
                'email'    => $email,
                'mobile'   => $mobile,
                'level'    => 1,
                'score'    => 0,
                'avatar'   => '',
            ];
            $params = array_merge($data, [
                'nickname'  => preg_match("/^1[3-9]{1}\d{9}$/",$username) ? substr_replace($username,'****',3,4) : $username,
                'salt'      => Random::alnum(),
                'jointime'  => $time,
                'joinip'    => $ip,
                'logintime' => $time,
                'loginip'   => $ip,
                'prevtime'  => $time,
                'status'    => 'normal'
            ]);

            $params['password'] = md5(md5($password) . $params['salt']);
            $params = array_merge($params, $extend);

            Db::startTrans();
            try {
                $user_model = new \app\admin\model\User;
                $result = $user_model->allowField(true)->insertGetId($params);
                Db::commit();
            } catch (ValidateException $e) {
                Db::rollback();
                return false;
            } catch (PDOException $e) {
                Db::rollback();
                return false;
            } catch (Exception $e) {
                Db::rollback();
                return false;
            }
            if ($result !== false) {
                $user_id = $result;
            } else {
                return false;
            }

        }else{
            $user_id = $info['id'];
        }

        return $user_id;
    }

    /**
     * 写入记录log
     */
    public function getWriteLog($title = ''){

        $data = [
            'admin_id' => $this->auth->id,
            'username' => $this->auth->username,
            'url'    =>  $this->request->url(),
            'title'   => $title,
            'content'    => [],
            'ip'    => request()->ip(),
            'useragent'   => '',
            'createtime'   => time(),
        ];

        $adminlog_model = new \app\admin\model\AdminLog;
        $result = $adminlog_model->allowField(true)->insertGetId($data);
        return $result;
    }

}
